package com.pharmacy.MedicineManage.controller;

import com.pharmacy.MedicineManage.entity.Medicine;
import com.pharmacy.MedicineManage.service.MedicineService;
import com.pharmacy.UserManage.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/medicine")
public class MedicineController {

    @Autowired
    private MedicineService medicineService;

    // 获取所有药品
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getAllMedicines(HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser == null) {
            response.put("success", false);
            response.put("message", "用户未登录");
            return ResponseEntity.status(401).body(response);
        }

        try {
            List<Medicine> medicines = medicineService.getAllMedicines();
            response.put("success", true);
            response.put("data", medicines);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取药品列表失败");
            return ResponseEntity.status(500).body(response);
        }
    }

    // 根据ID获取药品
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getMedicineById(@PathVariable Integer id, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser == null) {
            response.put("success", false);
            response.put("message", "用户未登录");
            return ResponseEntity.status(401).body(response);
        }

        Medicine medicine = medicineService.getMedicineById(id);
        if (medicine != null) {
            response.put("success", true);
            response.put("data", medicine);
            return ResponseEntity.ok(response);
        } else {
            response.put("success", false);
            response.put("message", "药品不存在");
            return ResponseEntity.notFound().build();
        }
    }

    // 添加药品（需要管理员权限）
    @PostMapping("/add")
    public ResponseEntity<Map<String, Object>> addMedicine(@RequestBody Medicine medicine, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser == null || !"admin".equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.status(403).body(response);
        }

        if (medicineService.addMedicine(medicine)) {
            response.put("success", true);
            response.put("message", "药品添加成功");
            return ResponseEntity.ok(response);
        } else {
            response.put("success", false);
            response.put("message", "药品编码已存在");
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 更新药品（需要管理员权限）
    @PutMapping("/update")
    public ResponseEntity<Map<String, Object>> updateMedicine(@RequestBody Medicine medicine, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser == null || !"admin".equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.status(403).body(response);
        }

        if (medicineService.updateMedicine(medicine)) {
            response.put("success", true);
            response.put("message", "药品更新成功");
            return ResponseEntity.ok(response);
        } else {
            response.put("success", false);
            response.put("message", "药品编码已存在或更新失败");
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 删除药品（需要管理员权限）
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<Map<String, Object>> deleteMedicine(@PathVariable Integer id, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser == null || !"admin".equals(currentUser.getRole())) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.status(403).body(response);
        }

        if (medicineService.deleteMedicine(id)) {
            response.put("success", true);
            response.put("message", "药品删除成功");
            return ResponseEntity.ok(response);
        } else {
            response.put("success", false);
            response.put("message", "药品删除失败");
            return ResponseEntity.badRequest().body(response);
        }
    }

    // 搜索药品
    @GetMapping("/search")
    public ResponseEntity<Map<String, Object>> searchMedicines(@RequestParam String name, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser == null) {
            response.put("success", false);
            response.put("message", "用户未登录");
            return ResponseEntity.status(401).body(response);
        }

        List<Medicine> medicines = medicineService.searchMedicinesByName(name);
        response.put("success", true);
        response.put("data", medicines);
        return ResponseEntity.ok(response);
    }

    // 按分类获取药品
    @GetMapping("/category/{category}")
    public ResponseEntity<Map<String, Object>> getMedicinesByCategory(@PathVariable String category, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser == null) {
            response.put("success", false);
            response.put("message", "用户未登录");
            return ResponseEntity.status(401).body(response);
        }

        List<Medicine> medicines = medicineService.getMedicinesByCategory(category);
        response.put("success", true);
        response.put("data", medicines);
        return ResponseEntity.ok(response);
    }

    // 检查药品编码是否存在
    @GetMapping("/checkCode")
    public ResponseEntity<Map<String, Object>> checkCode(@RequestParam String code) {
        Map<String, Object> response = new HashMap<>();
        boolean exists = medicineService.isCodeExist(code);
        response.put("success", true);
        response.put("exists", exists);
        return ResponseEntity.ok(response);
    }
}